﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Drawing.Design;
using System.ComponentModel;

namespace UmcControls.DesignInterface
{
    internal interface IToolboxItemManager
    {
        IEnumerable<Type> GetAllPossibleItemType();
    }

    internal class ToolboxItemManager : IToolboxItemManager
    {
        #region IToolboxItemManager Members

        public IEnumerable<Type> GetAllPossibleItemType()
        {
            List<Type> retList = new List<Type>();

            foreach (Type possibleItem in Assembly.GetExecutingAssembly().GetTypes())
            {
                //if config file do not define
                if (!IsDefinedInConfig(possibleItem))
                    continue;
                // A toolbox item must implement IComponent and must not be abstract.
                if (!typeof(IComponent).IsAssignableFrom(possibleItem) ||
                    possibleItem.IsAbstract)
                    continue;
                // A toolbox item must have a constructor that takes a parameter of
                // type Type or a constructor that takes no parameters.
                if (null == possibleItem.GetConstructor(new Type[] { typeof(Type) }) &&
                    null == possibleItem.GetConstructor(new Type[0]))
                    continue;
                AttributeCollection attribs = TypeDescriptor.GetAttributes(possibleItem);
                //only define [ToolboxItem(true)] is allowed
                ToolboxItemAttribute tba =
                    attribs[typeof(ToolboxItemAttribute)] as ToolboxItemAttribute;
                if (tba != null && !tba.Equals(ToolboxItemAttribute.None))
                {
                    retList.Add(possibleItem);
                }
            }
            return retList;
        }

        #endregion

        //TODO : implement a config file scan
        private bool IsDefinedInConfig(Type type)
        {
            return true;
        }
    }
}
